package pbl;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class PersonClient {

	public static void main(String[] args) throws Exception {
		
		Person p1 = new Person("Ole Olsen", 63);
	    Person p2 = new Person("John Doe", 34);
	    Person p3 = new Person("Belinda Hart", 14);
	    Person p4 = new Person("George Smith", 89);
	    System.out.println("Stating clintprogram...");
	    addPerson( new Person("Ole Olsen", 63) );
	    System.out.println( fetchPerson(0) );
	  }	
	
	public static void addPerson(Person person) throws Exception
	{
		InetAddress serverAddress = InetAddress.getByName("localhost");
	    int serverPort = 6000;
	    Socket socket = new Socket( serverAddress, serverPort );
	    OutputStream os = socket.getOutputStream();
	    ObjectOutputStream oos = new ObjectOutputStream( os );
	    
	    oos.writeObject( new Integer(1) );
	    oos.writeObject( person );
	    oos.flush();
	    socket.close();
    }
	
	public static Person fetchPerson(int index) throws Exception 
	{	
		InetAddress serverAddress = InetAddress.getByName("localhost");
	    int serverPort = 7000;
	    Socket socket = new Socket( serverAddress, serverPort );
	    OutputStream os = socket.getOutputStream();
	    ObjectOutputStream oos = new ObjectOutputStream( os );
	    InputStream is = socket.getInputStream();
	    ObjectInputStream ois = new ObjectInputStream( is );
	    
    	oos.writeObject( new Integer(2) );
    	Person person = (Person) ois.readObject();
    	socket.close();
    	return person;
	}
	
}
